import { createSlice } from "@reduxjs/toolkit";
import { removeToken } from "@/utils";
import { setToken as _setToken, getToken } from "@/utils";
import { getUserInfoAPI, loginAPI } from "@/api/user";

const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo: {},
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      _setToken(action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state, _action) {
      state.token = "";
      state.userInfo = {};
      removeToken();
    },
  },
});

const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

const handleLogin = (form) => {
  return async (dispatch) => {
    const response = await loginAPI(form);
    dispatch(setToken(response.data.token));
  };
};

const handleGetUserInfo = () => {
  return async (dispatch) => {
    const response = await getUserInfoAPI();
    dispatch(setUserInfo(response.data));
  };
};

export { handleLogin, handleGetUserInfo, clearUserInfo };

export default userStore.reducer;
